//
//  DeliveryDetailViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-11-14.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "DeliveryDetailViewController.h"
#import "DropDownListView.h"
#import "AddressModel.h"
#import "RegisterHelper.h"
#import "DeliveryViewController.h"

@interface DeliveryDetailViewController ()<DropDownChooseDelegate,DropDownChooseDataSource>
{
    NSMutableArray *chooseArray ;

}
@property(nonatomic,assign)NSInteger lastProviIndex;
@property(nonatomic,assign)NSInteger lastCityIndex;
@property(nonatomic,strong)DropDownListView * dropDownView;


@end

@implementation DeliveryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     _isEidt = NO;
    
    [self setTitleView:@"添加或修改地址"];
    
    _chooseTableView = [[UITableView alloc]initWithFrame:CGRectMake(20, 0, kWidth - 40, 400) style:UITableViewStylePlain];
    _chooseTableView.dataSource = self;
    _chooseTableView.delegate = self;
    _chooseTableView.backgroundColor = [UIColor whiteColor];
    _chooseTableView.alpha = 1;
    _chooseTableView.scrollEnabled = NO;
    [self.view addSubview:_chooseTableView];
    
    CGSize size = [@"保存" getSizeOfStringFontSize:16 constroSize:CGSizeMake(120, MAXFLOAT)];
    _saveButton = [UnitToolCommonView viewWithButtonWithText:@"保存" textColor:[UIColor whiteColor] frame:CGRectMake(0, 0, size.width, 40)];
    [_saveButton addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    _saveButton.userInteractionEnabled = YES;
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithCustomView:_saveButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
   _provinceArray = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];
    
    _cityArray = [[_provinceArray objectAtIndex:0] objectForKey:@"cities"];

    NSArray *citiesArray = [[_cityArray objectAtIndex:0]objectForKey:@"city"];
    NSLog(@"%@",citiesArray);
    
    _sectionArray = [[_cityArray objectAtIndex:0]objectForKey:@"areas"];
    NSLog(@"%@",_sectionArray);
    
    
    // Do any additional setup after loading the view.
}

-(void)tapAction{
    
    [_nameTextField resignFirstResponder];
    [_phoneTextField resignFirstResponder];
    [_addressTextField resignFirstResponder];
    [_codeTextField resignFirstResponder];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentitfer"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentitfer"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
   
    
    if (indexPath.row == 0) {
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,120, 20)];
        addressLabel.text =@"添加新地址";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
    }else if (indexPath.row == 1){
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,40, 20)];
        addressLabel.text =@"姓名";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
        _nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(addressLabel.right + 10, 10, 200, 20)];
        _nameTextField.text = _addressModel.name;
        _nameTextField.delegate = self;
        _nameTextField.font = [UIFont systemFontOfSize:16.0f];
        _nameTextField.backgroundColor = [UIColor clearColor];
        _nameTextField.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:_nameTextField];
        
    }else if (indexPath.row == 2){
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,40, 20)];
        addressLabel.text =@"手机";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
        _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(addressLabel.right + 10, 10, 200, 20)];
        _phoneTextField.text = _addressModel.phone;
        _phoneTextField.delegate = self;
        //_phoneTextField.keyboardType =  UIKeyboardTypeNumberPad;
        _phoneTextField.font = [UIFont systemFontOfSize:15.0f];
        _phoneTextField.backgroundColor = [UIColor clearColor];
        _phoneTextField.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:_phoneTextField];
        
    }else if (indexPath.row == 3){
        
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,40, 20)];
        addressLabel.text =@"地区";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
        
        chooseArray = [NSMutableArray arrayWithArray:@[
                                                       _provinceArray,
                                                       _cityArray,
                                                       _sectionArray
                                                       ]];
        
        _dropDownView = [[DropDownListView alloc] initWithFrame:CGRectMake(addressLabel.right,0, SCREEN_WIDTH - addressLabel.width - 55, 40) dataSource:self delegate:self];
        _dropDownView.mSuperView = self.view;
        _dropDownView.type = DropViewListCellType;
        [cell.contentView addSubview:_dropDownView];
        
//        self.province = chooseArray[0][0];
//        self.city = chooseArray[1][0];
//        self.section = chooseArray[2][0];
        
    }else if (indexPath.row == 4){
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,40, 20)];
        addressLabel.text =@"地址";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
        _addressTextField = [[UITextField alloc]initWithFrame:CGRectMake(addressLabel.right + 10, 10, 200, 20)];
        _addressTextField.text = _addressModel.address;
        _addressTextField.delegate = self;
        _addressTextField.font = [UIFont systemFontOfSize:15.0f];
        _addressTextField.backgroundColor = [UIColor clearColor];
        _addressTextField.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:_addressTextField];
        
    }else if (indexPath.row == 5){
        
        UILabel *addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10,40, 20)];
        addressLabel.text =@"邮编";
        [cell.contentView addSubview:addressLabel];
        addressLabel.font = [UIFont systemFontOfSize:16.0f];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.textColor = UIColorFromRGB(0x9fa0a0);
        
        _codeTextField = [[UITextField alloc]initWithFrame:CGRectMake(addressLabel.right + 10, 10, 200, 20)];
        _codeTextField.text = _addressModel.code;
        _codeTextField.delegate = self;
        _codeTextField.font = [UIFont systemFontOfSize:15.0f];
        _codeTextField.backgroundColor = [UIColor clearColor];
        _codeTextField.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:_codeTextField];
        
    }else{
        
        _chooseButton = [[UIButton alloc]initWithFrame:CGRectMake(15, 10,20, 20)];
        [cell.contentView addSubview:_chooseButton];
        _chooseButton.font = [UIFont systemFontOfSize:16.0f];
        _chooseButton.backgroundColor = [UIColor clearColor];
        [_chooseButton addTarget:self action:@selector(chooseButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_chooseButton setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        
       
        
        UILabel *textField = [[UILabel alloc]initWithFrame:CGRectMake(_chooseButton.right + 20, 10, 200, 20)];
        textField.text = @"设置为默认收货地址";
        textField.font = [UIFont systemFontOfSize:15.0f];
        textField.backgroundColor = [UIColor clearColor];
        textField.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:textField];
        
    }
    
    return cell;
}

#pragma mark - chooseButtonAction
-(void)chooseButtonAction{
    
    if (_isEidt == NO) {
        
       [_chooseButton setImage:[UIImage imageNamed:@"choose_select_org.png"] forState:UIControlStateNormal];
        _isEidt = YES;
    }else{
        
       [_chooseButton setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        _isEidt = NO;
    }
}

#pragma mark -- dropDownListDelegate
-(void)chooseAtSection:(NSInteger)section index:(NSInteger)index dropListView:(DropDownListView *)dropListView
{
    NSLog(@"童大爷选了section:%d ,index:%d",section,index);
  
    switch (section) {
        case 0:
        {
            
            self.province = [[chooseArray[section] objectAtIndex:index]objectForKey:@"state"];
//            [[_cityArray objectAtIndex:section]objectForKey:@"city"];
//            [_dropDownView.mTableView reloadData];
            //设置市默认值0
            NSArray *citiesArray = [[_provinceArray objectAtIndex:_lastProviIndex] objectForKey:@"cities"];
            NSString* city = [[citiesArray objectAtIndex:0] objectForKey:@"city"];
            UIButton *currentCityBtn = (UIButton *)[_dropDownView viewWithTag:SECTION_BTN_TAG_BEGIN + section+1];
            [currentCityBtn setTitle:city forState:UIControlStateNormal];
            
            //设置区默认值0
            NSArray *areasArray = [[citiesArray objectAtIndex:0] objectForKey:@"areas"];
            NSString * area;
            if(areasArray.count == 0){
                area = @"无";
            }else{
                area = [areasArray objectAtIndex:0];
            }
            
            UIButton *currentSectionBtn = (UIButton *)[_dropDownView viewWithTag:SECTION_BTN_TAG_BEGIN + section+2];
            [currentSectionBtn setTitle:area forState:UIControlStateNormal];
        }
        break;
        case 1:{
            
            //设置区默认值0
            NSArray *citiesArray = [[_provinceArray objectAtIndex:_lastProviIndex] objectForKey:@"cities"];
            self.city = [[citiesArray objectAtIndex:index] objectForKey:@"city"];
            NSArray *areasArray = [[citiesArray objectAtIndex:index] objectForKey:@"areas"];
            NSString * area;
            if(areasArray.count == 0){
                area = @"无";
                self.section = @"\n";
            }else{
                area = [areasArray objectAtIndex:0];
            }
            UIButton *currentSectionBtn = (UIButton *)[_dropDownView viewWithTag:SECTION_BTN_TAG_BEGIN + section+1];
            [currentSectionBtn setTitle:area forState:UIControlStateNormal];
            
        }break;
        case 2:{
            
        self.section = [[[_cityArray objectAtIndex:_lastCityIndex] objectForKey:@"areas"] objectAtIndex:index];
            
        }break;
        default:
        break;
    }
    

}

#pragma mark -- dropdownList DataSource
-(NSInteger)numberOfSections:(DropDownListView *)dropListView
{
    return [chooseArray count];
}
-(NSInteger)numberOfRowsInSection:(NSInteger)section dropListView:(DropDownListView *)dropListView
{
    if (section == 0) {
        return _provinceArray.count;
    }else if (section == 1){
        NSArray *citiesArray = [[_provinceArray objectAtIndex:_lastProviIndex] objectForKey:@"cities"];
        return citiesArray.count;
    }else{
        NSArray *areasArray = [[_cityArray objectAtIndex:_lastCityIndex] objectForKey:@"areas"];
        return areasArray.count;
//        return _sectionArray.count;
        
    }

}

-(NSString *)titleInSection:(NSInteger)section index:(NSInteger)index dropListView:(DropDownListView *)dropListView
{
    if (section == 0) {
        _lastProviIndex = index;
       return [[_provinceArray objectAtIndex:index] objectForKey:@"state"];
        
    }else if (section == 1){
        _lastCityIndex = index;
        
        NSArray *citiesArray = [[_provinceArray objectAtIndex:_lastProviIndex] objectForKey:@"cities"];
        _cityArray = citiesArray;
        NSString* city = [[citiesArray objectAtIndex:index] objectForKey:@"city"];
        if(city.length == 0)
            return @"";
        
        return city;
        
    }else if (section == 2){
        
        NSArray *areasArray = [[_cityArray objectAtIndex:_lastCityIndex] objectForKey:@"areas"];
        if(areasArray.count == 0){
            return @"";
        }
        NSString * area = [areasArray objectAtIndex:index];
//        if ([_sectionArray count] > 0) {
//            return [_sectionArray objectAtIndex:_lastCityIndex];
//        }else{
//            return @"无";
//        }
        if(area.length == 0){
            return @"";
        }
        return area;
    }
    return 0;
}
-(NSInteger)defaultShowSection:(NSInteger)section dropListView:(DropDownListView *)dropListView
{
    return 0;
}

#pragma tableviewdelegate&datasourse

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 6) {
        
        return tableView.width - 44;
    }
    return 44;
}

//条件选择
-(void)mmDownMenuDidSelectWithCol:(NSInteger)col withRow:(NSInteger)row;
{
    NSLog(@"col %d row %d",col,row);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}

#pragma mark confirmAction 添加或修改地址
-(void)confirmAction{
    
    [self tapAction];
    if (self.nameTextField.text == nil || self.phoneTextField.text == nil || self.province == nil || self.city== nil || self.codeTextField.text == nil ) {
        
        [self showToastMessage: @"信息填写不完整!"];
        return;
        
    }else{
        
        _saveButton.userInteractionEnabled = NO;
        if (_isModify) {
            
            [self getEditAddressList:YES];
            
        }else{
            
            [self getEditAddressList:NO];
        }
    }
}


#pragma mark getEditAddressList  添加或修改地址
-(void)getEditAddressList:(BOOL)isModify{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (isModify) {
        NSString *shipId = self.addressModel.shipId;
        SetValueForKey(params, shipId, @"shipId");
    }
    NSString *userId = [RegisterHelper shareHelper].userId;
    NSString *defaultAddr;
    if (self.isEidt) {
        defaultAddr = @"true";
    }else{
        defaultAddr = @"false";
    }
    
    SetValueForKey(params, userId, @"userId");
    SetValueForKey(params, self.nameTextField.text, @"consignee");
    SetValueForKey(params, self.phoneTextField.text, @"tel");
    SetValueForKey(params, self.province, @"province");
    SetValueForKey(params, self.city, @"city");
    SetValueForKey(params, self.section, @"area");
    SetValueForKey(params, self.addressTextField.text, @"specificAddr");
    SetValueForKey(params, self.codeTextField.text, @"postcode");
    SetValueForKey(params, defaultAddr, @"defaultAddr");
    
    __weak DeliveryDetailViewController *weak_self  = self;
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kAddressEdit
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                        
                         NSDictionary *responseDic = request.responseJSON;
                         
                         if (response.isError) {
                             DLog(@"error %@",response.errorMessage);
                            weak_self.hud.labelText = [responseDic objectForKey:@"msg"];
                         }else{
                           
                             DLog(@"成功数据:%@",responseDic);
                                 
                                 if (weak_self.delegate && [weak_self.delegate respondsToSelector:@selector(commitAddress)]) {
                                     
                                     [weak_self.delegate commitAddress];
                                 }
                                 [weak_self.navigationController popViewControllerAnimated:YES];
                         }
                     }];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
